<template>
  <div>
    <div style="display:flex;flex-direction:row-reverse;margin-top:10px">
      <el-button :disabled="submitLoading" size="mini" type="primary" @click="submitForm(0)">保存</el-button>
      <el-button style="margin-right:20px" :disabled="submitLoading" size="mini" type="primary" @click="submitForm(1)">提交</el-button>
    </div>
    <div v-loading="dataLoading">
      <base-info :base-info="detailData" />
      <!-- <drawing-info :base-info="detailData" /> -->
      <distribute :base-info="detailData" />
      <config-info :base-info="detailData" />
      <studio-confirm :base-info="detailData" />
      <config-info :config-type="1" :base-info="detailData" />
      <!-- 转化分配 -->
      <trans-distribute :base-info="detailData" />
    </div>
    <div style="margin-top:20px" class="qup-title-box"><span class="border" /><span>图纸转化信息</span></div>
    <el-form
      :model="formData"
      size="mini"
      label-width="150px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="产品最终下单时间:" prop="productFinalOrderTime">
            <el-input v-model="formData.productFinalOrderTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin:10px 0">
      <el-button size="mini" type="primary" @click="handleAdd">新增</el-button>
      <el-button size="mini" type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
    </div>
    <el-table
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      show-overflow-tooltip
      border
      :data="formData.autonomyDesignExceptionDTOList"
      style="width: 90%"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="drawNum" label="绘制数量" min-width="100">
        <template slot-scope="scope">
          <!-- @input="(data)=>{data>0?scope.row.exception='':''}"  -->
          <el-input-number v-if="scope.row.addFlag||(nowTime().substring(0,10)===(scope.row.createTime&&scope.row.createTime.substring(0,10)))" v-model="scope.row.drawNum" :min="0" @change="changeNumber(scope.$index)" />
          <span v-else>{{ scope.row.drawNum }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" label="异常情况描述" min-width="150">
        <template slot-scope="scope">
          <!-- @input="(data)=>{data.length>0?scope.row.drawNum=0:''}" -->
          <el-input v-if="scope.row.addFlag||(nowTime().substring(0,10)===(scope.row.createTime&&scope.row.createTime.substring(0,10)))" v-model="scope.row.exception" />
          <span v-else>{{ scope.row.exception }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" min-width="80" />
      <el-table-column prop="createTime" label="创建时间" min-width="120" />
      <el-table-column prop="lastUpdateBy" label="修改人" min-width="80" />
      <el-table-column prop="lastUpdateTime" label="修改时间" min-width="120" />
    </el-table>
    <div style="margin:10px 0">
      <el-button size="mini" type="primary" @click="handleAddNumber">新增</el-button>
      <el-button size="mini" type="primary" @click="handleDelNumber">删除</el-button>
      <el-button size="mini" type="primary" :loading="saveNumberLoading" @click="handleSaveNumber">保存</el-button>
    </div>
    <div style="padding-bottom:20px">
      <el-table
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        show-overflow-tooltip
        border
        height="200"
        :data="formData.autonomyDesignCrmDTOList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" label="" width="60" />
        <el-table-column prop="" label="工单流水号" min-width="130">
          <template slot-scope="scope">
            <el-input v-if="scope.row.addFlag" v-model="scope.row.serialCode" @change="searchSerialCode(scope.row.serialCode,scope.$index)" />
            <span v-else>{{ scope.row.serialCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" show-overflow-tooltip label="CRM下单时间" min-width="120" />
        <el-table-column prop="confirmTime" show-overflow-tooltip label="CRM确图时间" min-width="120" />
        <el-table-column prop="quotationTime" show-overflow-tooltip label="商家确认报价时间" min-width="120" />
        <el-table-column prop="remark" show-overflow-tooltip label="备注" min-width="80" />
        <el-table-column prop="unLockTime" show-overflow-tooltip label="解锁时间" min-width="120" />
        <el-table-column prop="status" label="订单状态" min-width="120">
          <template slot-scope="scope">
            {{ formaterData(statusOptions,scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" min-width="80" />
        <el-table-column prop="createTime" show-overflow-tooltip label="创建时间" min-width="120" />
        <el-table-column min-width="130" fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click.native.prevent="handleProduct(scope.row,scope.$index)">查看产品</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <dlg-form v-if="dialogVisible" :code="activeCode" :visible.sync="dialogVisible" />

  </div>
</template>
<script>
import { formaterData } from '@/utils'
import dlgForm from './component/ProductDlg.vue'
import BackPageMixin from '@/mixins/backPage'
import { queryDetail, submitCrmOrder, queryCrmByCode } from '@/api/autoDesignTask'
import baseInfo from './component/BaseInfo.vue'
import drawingInfo from './component/DrawingInfo.vue'
import distribute from './component/distributeInfo.vue'
import configInfo from './component/ConfigInfo.vue'
import studioConfirm from './component/StudioConfirm'
import transDistribute from './component/TransDistribute'
import { nowTime } from '@/utils/tool'
import { getDictList } from '@/api/dataDict'

export default {
  name: 'TransDistribute',
  components: { dlgForm, baseInfo, drawingInfo, distribute, configInfo, studioConfirm, transDistribute },
  mixins: [BackPageMixin],
  props: {
  },
  data() {
    return {
      id: '',
      nowTime,
      formaterData,
      activeCode: '',
      statusOptions: [],
      dialogVisible: false,
      allAutoDesignPic: 0,
      detailData: {},
      people: [],
      tableSelected: [],
      submitLoading: false,
      dataLoading: false,
      saveLoading: false,
      saveNumberLoading: false,
      delList: [], // 工单流水号删除
      formData: {
        id: '',
        productFinalOrderTime: '',
        autonomyDesignExceptionDTOList: [],
        autonomyDesignCrmDTOList: []
      }
    }
  },
  watch: {
  },
  async  created() {
    this.id = this.$route.query.id
    if (this.id) {
      this.dataLoading = true
      queryDetail(this.id).then(res => {
        if (res.success) {
          this.detailData = res.data
          const { drawingChangeTime, id } = res.data
          this.formData = { drawingChangeTime, id }
          this.$set(this.formData, 'autonomyDesignExceptionDTOList', JSON.parse(JSON.stringify(res.data.autonomyDesignExceptionDTOList || [])))
          this.formData.autonomyDesignExceptionDTOList = this.formData.autonomyDesignExceptionDTOList.map(v => { return { ...v, drawNum: v.drawNum || undefined, exception: v.exception || '' } })
          this.$set(this.formData, 'autonomyDesignCrmDTOList', JSON.parse(JSON.stringify(res.data.autonomyDesignCrmDTOList || [])))
          this.allAutoDesignPic = 0
          const temp = res.data.drawingConfigDTOList.filter(v => v.configType === 1)
          if (temp.length > 0) {
            temp[0].autonomyDesignBusinessDTOList.forEach(v => { this.allAutoDesignPic += (v.productNum && Number(v.productNum)) || 0 })
          }
          this.dataLoading = false
        }
      })
    }
    getDictList({ dictTypeCode: 'CRM_PURCHASE_ORDER_STATUS' }, 'top2-crm', 'marketing').then(res => {
      if (res.success) {
        this.statusOptions = res.data
      }
    })
    this.dataLoading = false
  },
  mounted() {
  },
  methods: {
    handleProduct(data) {
      if (data.disableFlag) {
        this.$message.warning('无效工单号')
        return
      }
      this.activeCode = data.serialCode
      this.dialogVisible = true
    },
    handleAdd() {
      const flag = this.formData.autonomyDesignExceptionDTOList.findIndex(v => (v.createTime && v.createTime.substring(0, 10)) === nowTime().substring(0, 10))
      if (flag !== -1) {
        this.$message.warning('当日已新增，只可修改')
        return
      }
      this.formData.autonomyDesignExceptionDTOList.push({ addFlag: true, drawNum: undefined, exception: '', createTime: nowTime() })
    },
    handleSave() {
      if (this.formData.autonomyDesignExceptionDTOList.length === 0) {
        this.$message.warning('请填写绘制数量或异常情况描述')
        return
      }
      const data = { id: this.formData.id,
        autonomyDesignCrmDTOList: this.formData.autonomyDesignCrmDTOList,
        autonomyDesignExceptionDTOList: this.formData.autonomyDesignExceptionDTOList }
      this.saveLoading = true
      submitCrmOrder(data, 0).then(res => {
        if (res.success) {
          this.saveLoading = false
          this.formData.autonomyDesignExceptionDTOList = res.data.data.autonomyDesignExceptionDTOList.map(v => { return { ...v, drawNum: v.drawNum || undefined, exception: v.exception || '' } })
          this.$message.success('操作成功')
        }
      }).catch(() => {
        this.saveLoading = false
      })
    },
    // 新增工单流水号
    handleAddNumber() {
      this.formData.autonomyDesignCrmDTOList.push({ addFlag: true, flagCode: Math.floor(Math.random() * 0xffffff).toString(16) })
    },
    // 删除工单流水号
    handleDelNumber() {
      if (this.tableSelected.length === 0) {
        this.$message.warning('请选择删除项')
        return
      }
      const flag = this.formData.autonomyDesignCrmDTOList.filter(item => {
        const index = this.tableSelected.findIndex(i => ((i.id && item.id && i.id === item.id) || (i.flagCode && item.flagCode && i.flagCode === item.flagCode)))
        return index === -1
      })
      this.formData.autonomyDesignCrmDTOList = flag
      this.delList = [...this.delList, ...this.tableSelected].filter(v => !v.flagCode)
    },
    // 保存工单流水号
    handleSaveNumber() {
      // if (this.formData.autonomyDesignCrmDTOList.length === 0) {
      //   this.$message.warning('请填写工单流水号')
      //   return
      // }
      this.formData.autonomyDesignCrmDTOList = this.formData.autonomyDesignCrmDTOList.filter(v => !v.disableFlag && v.serialCode)
      const list = [...this.formData.autonomyDesignCrmDTOList, ... this.delList.map(v => { return { ...v, dr: 1 } })]
      if (list.length === 0) {
        this.$message.warning('请填写工单流水号')
        return
      }
      const data = { id: this.formData.id,
        autonomyDesignExceptionDTOList: this.formData.autonomyDesignExceptionDTOList,
        autonomyDesignCrmDTOList: list }
      this.saveNumberLoading = true
      submitCrmOrder(data, 0).then(res => {
        if (res.success) {
          this.saveNumberLoading = false
          this.formData.autonomyDesignCrmDTOList = res.data.data.autonomyDesignCrmDTOList

          this.$message.success('操作成功')
        }
      }).catch(() => {
        this.saveNumberLoading = false
      })
    },
    handleSelectionChange(data) {
      this.tableSelected = data
    },
    // 查询crm工单流水号信息
    searchSerialCode(data, index) {
      queryCrmByCode(data).then(res => {
        if (res.success && res.data.records.length > 0) {
          const obj = {
            serialCode: this.formData.autonomyDesignCrmDTOList[index].serialCode,
            addFlag: this.formData.autonomyDesignCrmDTOList[index].addFlag,
            orderTime: res.data.records[0].createTime, // 下单时间
            flagCode: this.formData.autonomyDesignCrmDTOList[index].flagCode,
            confirmTime: res.data.records[0].confirmDrawingExamineTime, // CRM确图时间
            quotationTime: res.data.records[0].offerPriceTime, // 商家确认报价时间
            remark: res.data.records[0].remark,
            unLockTime: res.data.records[0].unLockTime, // 解锁时间todo
            status: res.data.records[0].stage, // 订单状态,crm叫做订单节点
            createBy: res.data.records[0].createBy,
            createTime: res.data.records[0].createTime,
            orderCode: res.data.records[0].kjlCustomerOrderCode
          }
          this.formData.autonomyDesignCrmDTOList.splice(index, 1, obj)
        } else {
          this.$set(this.formData.autonomyDesignCrmDTOList[index], 'disableFlag', true)
          this.$message.warning('无效单号，请检查')
        }
      })
    },
    handleChangePeople(data) {
      if (data && data.length > 0) {
        const list = data.map(v => v.userName)
        this.$set(this.formData, 'drawingChanger', list.join(','))
      } else {
        this.$set(this.formData, 'drawingChanger', '')
      }
    },
    goBack() {
      this.$store.dispatch('views/goBack')
    },
    changeNumber(index) {
      let total = 0
      this.formData.autonomyDesignExceptionDTOList.forEach(v => {
        total += (v.drawNum && Number(v.drawNum)) || 0
      })
      if (total > this.allAutoDesignPic) {
        this.$message.warning('绘制数量总和已大于产品设计个数' + this.allAutoDesignPic)
        this.formData.autonomyDesignExceptionDTOList[index].drawNum = 0
        return
      }
    },
    submitForm(type) {
      if (this.submitLoading) return

      if (type === 1) {
        this.$set(this.formData, 'productFinalOrderTime', nowTime())
      }
      this.formData.autonomyDesignCrmDTOList = this.formData.autonomyDesignCrmDTOList.filter(v => !v.disableFlag && v.serialCode)
      this.submitLoading = true
      submitCrmOrder(this.formData, type).then(res => {
        if (res.success && !res.data.success) {
          this.$message.warning(res.data.msg)
        } else if (res.success) {
          this.$message.success('操作成功')
          this.goBack()
        }
        this.submitLoading = false
      }).catch(() => {
        this.submitLoading = false
      })
    }

  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
</style>
